<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 头部警告区域 -->
      <el-alert :closable="false" title="注意：只允许为第三级分类设置相关参数！" type="warning" show-icon></el-alert>
      <!-- 商品分类级联选择框 -->
      <el-row class="cat_opt">
        <el-col>
          <span>选择商品分类:</span>
          <!-- 级联选择框 -->
          <el-cascader
            expand-trigger="hover"
            v-model="cateListKeys"
            :options="cateList"
            :props="cateListProps"
            @change="cateListChange"
          ></el-cascader>
        </el-col>
      </el-row>
      <!-- tab页签区域 -->
      <el-tabs v-model="activeName" @tab-click="tabHandleClick">
        <!-- 添加动态参数的面板 -->
        <el-tab-pane label="动态参数" name="many">
          <el-button
            size="small"
            type="primary"
            :disabled="isDisabled"
            @click="addParamsDialog=true"
          >添加参数</el-button>
          <!-- 动态参数表格 -->
          <el-table :data="manyData" border stripe>
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- tag标签 -->
                <el-tag
                  closable
                  v-for="(item,i) in scope.row.attr_vals"
                  :key="i"
                  @close="handleClose(i,scope.row)"
                >{{item}}</el-tag>
                <!-- 输入框和按钮 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >+ New Tag</el-button>
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  size="mini"
                  icon="el-icon-edit"
                  @click="showEditDialog(scope.row.attr_id)"
                >修改</el-button>
                <el-button
                  type="danger"
                  size="mini"
                  icon="el-icon-delete"
                  @click="removeParams(scope.row.attr_id)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!-- 添加静态属性的面板 -->
        <el-tab-pane label="静态属性" name="only">
          <el-button
            size="small"
            type="primary"
            :disabled="isDisabled"
            @click="addParamsDialog=true"
          >添加属性</el-button>
          <!-- 静态属性表格 -->
          <el-table :data="onlyData" border stripe>
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- tag标签 -->
                <el-tag
                  closable
                  v-for="(item,i) in scope.row.attr_vals"
                  :key="i"
                  @close="handleClose(i,scope.row)"
                >{{item}}</el-tag>
                <!-- 输入框和按钮 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >+ New Tag</el-button>
              </template>
            </el-table-column>

            <!-- 索引列 -->
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column label="静态属性" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  size="mini"
                  icon="el-icon-edit"
                  @click="showEditDialog(scope.row.attr_id)"
                >修改</el-button>
                <el-button
                  type="danger"
                  size="mini"
                  icon="el-icon-delete"
                  @click="removeParams(scope.row.attr_id)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
      <!-- 添加参数对话框 -->
      <el-dialog
        :title="'添加'+ titleDiaLog"
        :visible.sync="addParamsDialog"
        width="50%"
        @close="addDialogClosed"
      >
        <!-- 添加参数对话框表单区域 -->
        <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px">
          <el-form-item :label="titleDiaLog" prop="attr_name">
            <el-input v-model="addForm.attr_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addParamsDialog = false">取 消</el-button>
          <el-button type="primary" @click="addParams">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 点击编辑对话框 -->
      <el-dialog
        :title="'修改'+ titleDiaLog"
        :visible.sync="editParamsDialog"
        width="50%"
        @close="editDialogClosed"
      >
        <!-- 添加参数对话框表单区域 -->
        <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="100px">
          <el-form-item :label="titleDiaLog" prop="attr_name">
            <el-input v-model="editForm.attr_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editParamsDialog = false">取 消</el-button>
          <el-button type="primary" @click="editParams">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>
<script>
export default {
  // 数据
  data() {
    return {
      // 分类列表
      cateList: [],
      //   绑定选择器的数组
      cateListKeys: [],
      //   定义props属性的绑定对象
      cateListProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      //   tab页签的双向绑定数据
      activeName: 'many',
      //   动态参数数据
      manyData: [],
      //  静态属性数据
      onlyData: [],
      //   添加参数的对话框显示隐藏
      addParamsDialog: false,
      //   添加参数的表单数据对象
      addForm: {
        attr_name: ''
      },
      //   添加参数表单验证规则
      addFormRules: {
        attr_name: [
          { required: true, message: '请添加参数名称', trigger: 'blur' }
        ]
      },
      //   修改参数对话框显示隐藏
      editParamsDialog: false,
      //   修改参数表单数据对象
      editForm: {},
      // 修改参数表单验证规则
      editFormRules: {
        attr_name: [
          { required: true, message: '请添加参数名称', trigger: 'blur' }
        ]
      }
    }
  },
  // 声明周期函数
  created() {
    this.getCateList()
  },
  // 方法
  methods: {
    async getCateList() {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) {
        this.$message.error('获取分类数据失败!')
      }
      this.cateList = res.data
      console.log(this.cateList)
    },
    // 监听级联选择器的值改变事件 控制选中项
    cateListChange() {
      this.getCateListAll()
    },
    // 点击tab页签 触发事件
    tabHandleClick() {
      this.getCateListAll()
    },
    // 定义获取分类数据函数  多处调用(点击tab栏和级联选择框值改变事件)
    async getCateListAll() {
      // 如果选择的分类选项小于三  就返回空数组
      if (this.cateListKeys.length !== 3) {
        this.cateListKeys = []
      }
      console.log(this.cateListKeys)
      //   级联选择器值改变就发送请求
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes`,
        {
          params: { sel: this.activeName }
        }
      )
      //   请求失败 给出提示
      if (res.meta.status !== 200) {
        this.$message.error('获取分类参数失败!')
      }
      //  把每一项数据用逗号分隔成数组
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(',') : []
        //   控制文本输入框的显示隐藏
        item.inputVisible = false
        // 文本输入框的值
        item.inputValue = ''
      })

      console.log(res.data)
      //   根据不同属性获取不同数据
      if (this.activeName === 'many') {
        this.manyData = res.data
      } else {
        this.onlyData = res.data
      }
    },
    // 添加参数对话框关闭事件
    addDialogClosed() {
      this.$refs.addFormRef.resetFields()
    },
    // 点击确定按钮  校验表单  发起请求
    addParams() {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) {
          this.$message.error('验证失败!')
        }
        const { data: res } = await this.$http.post(
          `categories/${this.cateId}/attributes`,
          {
            attr_name: this.addForm.attr_name,
            attr_sel: this.activeName
          }
        )
        if (res.meta.status !== 201) {
          this.$message.error('创建分类参数失败!')
        }
        this.$message.success('添加分类参数成功!')
        this.getCateListAll()
        this.addParamsDialog = false
      })
    },
    // 点击修改对话框
    async showEditDialog(attrId) {
      const {
        data: res
      } = await this.$http.get(
        `categories/${this.cateId}/attributes/${attrId}`,
        { params: { attr_sel: this.activeName } }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('修改参数失败!')
      }
      this.editForm = res.data
      this.editParamsDialog = true
    },
    // 修改对话框关闭事件
    editDialogClosed() {
      this.$refs.editFormRef.resetFields()
    },
    // 点击确定修改信息
    editParams() {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return
        const {
          data: res
        } = await this.$http.put(
          `categories/${this.cateId}/attributes/${this.editForm.attr_id}`,
          { attr_name: this.editForm.attr_name, attr_sel: this.activeName }
        )
        if (res.meta.status !== 200) {
          this.$message.error('修改参数失败!')
        }
        this.$message.success('修改参数信息成功!')
        this.getCateListAll()
        this.editParamsDialog = false
      })
    },
    //  删除分类参数
    async removeParams(attrId) {
      // 先给出提示
      const confirmResult = await this.$confirm(
        '此操作将永久删除该分类, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      if (confirmResult !== 'confirm') {
        return this.$message.info('取消了本次删除!')
      }
      const { data: res } = await this.$http.delete(
        `categories/${this.cateId}/attributes/${attrId}`
      )
      if (res.meta.status !== 200) this.$message.error('删除参数失败!')
      this.$message.success('删除参数成功!')
      this.getCateListAll()
    },
    // tag标签事件
    handleInputConfirm(row) {
      // 如果输入框没有内容  重置输入框 并隐藏
      if (row.inputValue.trim().length === 0) {
        row.inputValue = ''
        row.inputVisible = false
        return
      }
      //   如果没有return 说明需要做后续的处理
      row.attr_vals.push(row.inputValue.trim())
      row.inputValue = ''
      row.inputVisible = false
      this.saveAttrVals(row)
    },
    // 定义函数  获取数据
    async saveAttrVals(row) {
      //   发送请求   保存数据到服务器
      const { data: res } = await this.$http.put(
        `categories/${this.cateId}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(',')
        }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('添加属性失败!')
      }
      this.$message.success('更新成功!')
    },
    // 删除tag分类
    handleClose(i, row) {
      row.attr_vals.splice(i, 1)
      this.saveAttrVals(row)
    },
    // 点击标签  显示输入框
    showInput(row) {
      row.inputVisible = true
      //   $nextTick方法  页面重新加载后会执行里面的回调函数
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    }
  },

  //   计算属性  计算依赖data数据的属性
  computed: {
    //   控制添加分类按钮的显示隐藏
    isDisabled() {
      if (this.cateListKeys.length !== 3) {
        return true
      } else {
        return false
      }
    },
    // 当前选中的三级分类的ID
    cateId() {
      if (this.cateListKeys.length === 3) {
        return this.cateListKeys[2]
      }
      return null
    },
    // 添加参数对话框提示信息
    titleDiaLog() {
      if (this.activeName === 'many') {
        return '动态参数'
      } else {
        return '静态属性'
      }
    }
  }
}
</script>
<style lang="less" scoped>
.cat_opt {
  margin-top: 15px;
}
.el-cascader {
  margin-left: 20px;
}
.el-tabs {
  margin-top: 20px;
}
.el-tag {
  margin: 10px;
}
.input-new-tag {
  width: 150px;
}
</style>
